#include "comet_message_outlet_service.h"

#include <sstream>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/shared_ptr.hpp>

namespace imserver {

extern boost::asio::io_service g_io_service;

class CometMessageOutletTask : public boost::enable_shared_from_this<CometMessageOutletTask> {
public:
  CometMessageOutletTask(const std::vector<int64_t>& uids, const ImMessage& message) : uids_(uids), message_(message) {}

  void Handle(int64_t uid, CometConnectionPtr conn) {
    LOG_INFO("MessageOutletTask::sendMessage --> receiver:" << uid);
    std::ostringstream rsp_header;
    std::ostringstream rsp_body;
    rsp_body << "{\"id\":\"" << message_.id
        << "\",\"type\":\"" << message_.type
        << "\",\"sender\":\"" << message_.sender
        << "\",\"receiver\":\"" << *it
        << "\",\"groupid\":\"" << message_.group_id
        << "\",\"timestamp\":\"" << message_.timestamp
        << "\",\"message\":\"" << base::JsonEscape(message_.body)
        << "\"}";
    rsp_header << "HTTP/1.1 200 OK\r\n"
        << "Content-Type: text/javascript; charset=utf-8\r\n"
        << "Connection: close\r\n"
        << "Content-Length: " << rsp_body.str().size() << "\r\n"
        << "\r\n";
    std::string response = rsp_header.str();
    response.append(rsp_body.str());
    conn->WriteResponse(response);
  }

  void Start() {
    std::vector<int64_t>::const_iterator it = uids_.begin();
    for (; it != uids_.end(); ++it) {
      CometConnectionPtr conn;
      if (UidCometConnMap::instance().get(*it, conn) && conn->isReadyForReceiveMsg()) {
        g_io_service.post(boost::bind(&CometMessageOutletTask::Handle, shared_from_this(), *it, conn));
      } else {
        // 用户不在线，发通知
        // ...
      }
    }
  }

private:
  std::vector<int64_t> uids_;
  ImMessage message_;
};

void CometMessageOutletServiceHandler::DistributeMessage(const std::vector<int64_t>& uids, const ImMessage& message) {
  boost::shared_ptr<CometMessageOutletTask> task(new CometMessageOutletTask(uids, message));
  task->Start();
}

}

